﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.IO;
//using NPOI.XWPF.UserModel;
using System.Diagnostics;
using Novacode;
using System.IO;
namespace Excel2doc
{
    class WhiteDoc
    {
        public void createdoc()
        {
            ;
        }

    }
    public class BookMarks
    {
        /// <summary>
        /// 书签Name
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// 书签文本
        /// </summary>
        public string Text
        {
            get;
            set;
        }

    }

    public class ExportWord
    {
        /// <summary>
        /// 导出word
        /// </summary>
        /// <param name="lBookMarks">书签数据源</param>
        /// <param name="sTemplatePath">导出Word模板文件</param>
        /// <param name="sFileName">导出文件名</param>
        public static void ToDocx(IEnumerable<BookMarks> lBookMarks, string sTemplatePath, string sFileName)
        {
            using (DocX document = DocX.Load(sTemplatePath))
            {
                List<Bookmark> booklist = new List<Bookmark>();
                foreach (Paragraph p in document.Paragraphs)
                {
                    booklist.AddRange(p.GetBookmarks());
                }

                foreach (BookMarks m in lBookMarks)
                {
                    foreach (Bookmark b in booklist)
                    {
                        if (b.Name == m.Name)
                        {
                            b.Paragraph.ReplaceText(b.Paragraph.Text, m.Text);
                        }
                    }
                }
                FileStream fs = new FileStream(sFileName, FileMode.Create);  
                document.SaveAs(fs);
                fs.Close();                
                //HttpContext.Current.Response.ContentType = "application/octet-stream";

                //string mybrowser = System.Web.HttpContext.Current.Request.Browser.Browser;
                //if (mybrowser.ToLower().IndexOf("firefox") > -1)//火狐浏览器
                //{
                //    HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.docx", sFileName));
                //}
                //else
                //{
                //    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(sFileName, System.Text.Encoding.UTF8) + ".docx\"");
                //}

                //HttpContext.Current.Response.Clear();

                //document.SaveAs(HttpContext.Current.Response.OutputStream);
                //HttpContext.Current.Response.End();

            }

        }
    }
}
